package yui.comn.hub.extension.crypt;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import com.alibaba.fastjson.JSONObject;

import yui.comn.hub.extension.utils.CryptAESUtils;
import yui.comn.hub.extension.utils.CryptBase64Utils;
import yui.comn.hub.extension.utils.StrCollUtils;
import yui.comn.hub.model.CryptMode;
import yui.comn.hub.model.CryptType;

public class CryptHandler {

	public static final String SECURITY_FIELD = "sf";
	public static final String SECURITY_MODE = "sm";
	
	public static HttpInputMessage handle(HttpInputMessage inputMessage, CryptType cryptType, CryptMode cryptMode) throws IOException {
		if (CryptType.PART == cryptType) {
			return getNew(inputMessage, partHandle(inputMessage, cryptType, cryptMode));
		} else if (CryptType.ALL == cryptType) {
			return getNew(inputMessage, allHandle(inputMessage, cryptType, cryptMode));
		}
		return inputMessage;
	}
	
	public static String partHandle(HttpInputMessage inputMessage, CryptType cryptType, CryptMode cryptMode) throws IOException {
		String bodyStr = IOUtils.toString(inputMessage.getBody(), "UTF-8");
        
        JSONObject parseObject = JSONObject.parseObject(bodyStr);
        if (parseObject.containsKey(SECURITY_FIELD)) {
        	String sfs = parseObject.getString(SECURITY_FIELD);
        	List<String> sfList = StrCollUtils.toStrList(sfs);
        	for (String sf : sfList) {
        		String sfVal = parseObject.getString(sf);
        		if (CryptMode.AES == cryptMode) {
        			sfVal = CryptAESUtils.decrypt(sfVal);
        		} else if (CryptMode.BASE64 == cryptMode) {
        			sfVal = CryptBase64Utils.decrypt(sfVal);
        		}
        		parseObject.put(sf, sfVal);
			}
        }
        
        return parseObject.toJSONString();
	}
	
	public static String allHandle(HttpInputMessage inputMessage, CryptType cryptType, CryptMode cryptMode) throws IOException {
		String bodyStr = IOUtils.toString(inputMessage.getBody(), "UTF-8");
		String bodyStrNew = null;
		if (CryptMode.AES == cryptMode) {
			bodyStrNew = CryptAESUtils.decrypt(bodyStr);
		} else if (CryptMode.BASE64 == cryptMode) {
			bodyStrNew = CryptBase64Utils.decrypt(bodyStr);
		}
		return bodyStrNew;
	}
	
	private static HttpInputMessage getNew(HttpInputMessage inputMessage, String body) {
		HttpInputMessage him = new HttpInputMessage() {
        	
        	@Override
        	public HttpHeaders getHeaders() {
        		return inputMessage.getHeaders();
        	}
        	
        	@Override
        	public InputStream getBody() throws IOException {
        		return IOUtils.toInputStream(body, "UTF-8");
        	}
        };
        return him;
	}
}
